/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
// 递归
class Solution {
private:
    vector<int> rst;
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if(root == nullptr){
            return rst;
        }

        rst.push_back(root->val);

        preorderTraversal(root->left);
        preorderTraversal(root->right);

        return rst;
    }
};

// 迭代-栈
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> rst;
        stack<TreeNode*> stack;

        if(root == nullptr){
            return rst;
        }
        
        stack.push(root);

        while(!stack.empty()){
            TreeNode* temp = stack.top();
            rst.push_back(temp->val);
            stack.pop();

            if(temp->right != nullptr){
                stack.push(temp->right);
            }

            if(temp->left != nullptr){
                stack.push(temp->left);
            }
        }

        return rst;
    }
};